
package com.x52im.rbchat.logic.sns_friend;

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.eva.android.widget.DataLoadableActivity;
import com.eva.android.widget.DataLoadingAsyncTask2;
import com.eva.android.widget.WidgetUtils;
import com.eva.epc.common.util.CommonUtils;
import com.eva.framework.dto.DataFromServer;
import com.x52im.rbchat.MyApplication;
import com.x52im.rbchat.R;
import com.x52im.rainbowchat.http.logic.dto.RosterElementEntity;
import com.x52im.rbchat.logic.alarm.AlarmType;
import com.x52im.rbchat.cache.AlarmsProvider;
import com.x52im.rbchat.logic.sns_group.GroupMemberActivity;
import com.x52im.rbchat.network.http.HttpRestHelper;
import com.x52im.rbchat.utils.BroadcastToolKits;
import com.x52im.rbchat.utils.IntentFactory;
import com.x52im.rbchat.utils.ToolKits;

import java.util.ArrayList;

public class FriendRemarkEditActivity extends DataLoadableActivity {

    private static final String TAG = FriendReqProcessActivity.class.getSimpleName();

    /** 输入组件：好友备注 */
    private EditText editRemark = null;
    /** 输入组件：手机号码 */
    private EditText editMobileNum = null;
    /** 输入组件：更多描述 */
    private EditText editMoreDesc = null;

    /** 文本组件：好友备注输入字数计数显示 */
    private TextView viewRemarkLengthCount = null;
    /** 文本组件：手机号码输入字数计数显示 */
    private TextView viewMobileNumLengthCount = null;
    /** 文本组件：更多描述输入字数计数显示 */
    private TextView viewMoreDescLengthCount = null;

    /** 按钮：确认 */
    private Button btnOK = null;

    /** 好友的uid（来自intent） */
    private String friendUidForInit = null;
    /** 好友列表中的好友信息对象引用 */
    private RosterElementEntity friendInfo = null;

    /**
     * {@inheritDoc}
     */
    @Override
    protected void initDataFromIntent() {
        //解析从intent中传过来的数据
        ArrayList intentDatas = IntentFactory.parseFriendRemarkEditIntent(getIntent());
        friendUidForInit = (String)intentDatas.get(0);
    }

    /**
     * 本方法由父类的onCreate()调用，子类可在此方法中实现自已的UI显示逻辑。
     */
    @Override
    protected void initViews(Bundle savedInstanceState) {
        // 设定自定义标题栏（设定此值即意味着开启自定义标题栏的使用，必须要在setContentView前设定）
        customeTitleBarResId = R.id.sns_friend_remark_edit_form_titleBar;
        // 养成良好习惯：首先设置主layout，确保后绪的操作中使用到的组件都可以被find到
        setContentView(R.layout.sns_friend_remark_edit_form);

        // 初始化各种组件
        editRemark = findViewById(R.id.sns_friend_remark_edit_form_remarkView);
        editMobileNum = findViewById(R.id.sns_friend_remark_edit_form_mobileNumView);
        editMoreDesc = findViewById(R.id.sns_friend_remark_edit_form_moreDescView);
        viewRemarkLengthCount = findViewById(R.id.sns_friend_remark_edit_form_remarkLengthCountView);
        viewMobileNumLengthCount = findViewById(R.id.sns_friend_remark_edit_form_mobileNumLengthCountView);
        viewMoreDescLengthCount = findViewById(R.id.sns_friend_remark_edit_form_moreDescLengthCountView);

        // 标题栏按钮实例
        btnOK = this.getCustomeTitleBar().getRightGeneralButton();
        // 设置标题栏按钮的ui样式
        GroupMemberActivity.setTextButtonStyleForTitle(this, btnOK);
        // 设置ok按钮的初始状态
        _setOkButtonEnable(false);

        // 设置标题
        this.setTitle(R.string.sns_friend_remark_edit_title);
        // 没什么需要load
        this.setLoadDataOnCreate(false);

        if(this.friendUidForInit != null){
            this.friendInfo = MyApplication.getInstance2().getIMClientManager().getFriendsListProvider().getFriendInfoByUid(this.friendUidForInit);
        }

        if(this.friendInfo == null){
            Log.w(TAG, "this.friendInfo == null！");
            WidgetUtils.showWithDialog(this, $$(R.string.general_prompt), $$(R.string.sns_friend_remark_edit_hint_for_invalide_data));
            this.finish();
        }

        // 刷新UI界面显示
        this.refreshToView(this.friendInfo);
    }

    /**
     * 本方法由父类的onCreate()调用，子类可在此方法中为各UI功能组件增加事件临听。
     */
    @Override
    protected void initListeners()
    {
        // 确认按钮事件处理
        btnOK.setOnClickListener(v -> {
            new DataAsyncTask().execute();
        });

        // 监听文本输入组件事件，并决定"保存"按钮的点击被点击
        TextWatcher tw = new TextWatcher(){
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                setOkButtonForChanged();
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        };
        this.editRemark.addTextChangedListener(tw);
        this.editMobileNum.addTextChangedListener(tw);
        this.editMoreDesc.addTextChangedListener(tw);

        // 添加事件监听，实现文本输入组件已输入字数实时计算和显示
        WidgetUtils.setTextLengthCounter(this.editRemark, this.viewRemarkLengthCount);
        WidgetUtils.setTextLengthCounter(this.editMobileNum, this.viewMobileNumLengthCount);
        WidgetUtils.setTextLengthCounter(this.editMoreDesc, this.viewMoreDescLengthCount);
    }

    @Override
    protected DataFromServer queryData(String... params) {
        return null;
    }

    @Override
    protected void refreshToView(Object dataToView) {
        if(dataToView != null && dataToView instanceof RosterElementEntity) {
            RosterElementEntity friendInfo = (RosterElementEntity)dataToView;

            this.editRemark.setText(friendInfo.getFriendRemark());
            this.editMobileNum.setText(friendInfo.getFriendMobileNum());
            this.editMoreDesc.setText(friendInfo.getFriendMoreDesc());
        }
        else {
            Log.w(TAG, "dateToView="+dataToView);
            WidgetUtils.showToast(this, "dateToView="+dataToView, WidgetUtils.ToastType.WARN);
        }

        // 将光标移至文字末尾
        WidgetUtils.setCursorToEnd(this.editRemark, true);
//        if(this.editRemark.getText() != null)
//            this.editRemark.setSelection(this.editRemark.getText().length());
//        this.editRemark.requestFocus();
    }

    /**
     * 输入内容是否改变。
     *
     * @return true表示已改变，否则未改变
     */
    private boolean contentHasChanged(){

        if(this.friendInfo == null)
            return false;

        String remark = this.editRemark.getText().toString().trim();
        String mobileNum = this.editMobileNum.getText().toString().trim();
        String moreDesc = this.editMoreDesc.getText().toString().trim();

        String oldRemark = this.friendInfo.getFriendRemark();
        String oldMobileNum = this.friendInfo.getFriendMobileNum();
        String oldMoreDesc = this.friendInfo.getFriendMoreDesc();

        boolean remarkChanged = (oldRemark != null && !oldRemark.equals(remark))
                || (oldRemark == null && !CommonUtils.isStringEmpty(remark));
        boolean mobileNumChanged = (oldMobileNum != null && !oldMobileNum.equals(mobileNum))
                || (oldMobileNum == null && !CommonUtils.isStringEmpty(mobileNum));
        boolean moreDescChanged = (oldMoreDesc != null && !oldMoreDesc.equals(moreDesc))
                || (oldMoreDesc == null && !CommonUtils.isStringEmpty(moreDesc));

        // 修改后的内容跟修改前的不相等才需要提交哦
        return remarkChanged || mobileNumChanged || moreDescChanged;
    }

    /**
     * 重置确认为初始状态：不可点击、文字内容显示为"确定"、以及按钮的UI样式为半透明效果。
     */
    private void _resetOkButton() {
        // 设置标题栏保存按钮的可用与禁用时样式
        GroupMemberActivity.setTextButtonEnableForTitle(this, this.btnOK, false);
        this.btnOK.setText($$(R.string.general_save));
    }

    /**
     * 决置确认按钮的可用性。
     *
     * @param enabled
     */
    private void _setOkButtonEnable(boolean enabled) {
        if(enabled) {
            // 设置标题栏保存按钮的可用与禁用时样式
            GroupMemberActivity.setTextButtonEnableForTitle(this, this.btnOK, true);
        }
        else {
            _resetOkButton();
        }
    }

    /**
     * 设置按钮是否可点击。
     */
    private void setOkButtonForChanged() {
        _setOkButtonEnable(contentHasChanged());
    }

    private class DataAsyncTask extends DataLoadingAsyncTask2<Object, Integer, DataFromServer>{

        public DataAsyncTask() {
            super(FriendRemarkEditActivity.this, $$(R.string.general_submitting));
        }

        /**
         * 在后台执行信息的提交和处于结果的读取 .
         *
         * @param params 外界传进来的参数
         * @return 查询结果，将传递给onPostExecute(..)方法
         */
        @Override
        protected DataFromServer doInBackground(Object... params) {
            RosterElementEntity localUserInfo = MyApplication.getInstance2().getIMClientManager().getLocalUserInfo();
            if(localUserInfo != null) {
                String remark = editRemark.getText().toString().trim();
                String mobileNum = editMobileNum.getText().toString().trim();
                String moreDesc = editMoreDesc.getText().toString().trim();
                return HttpRestHelper.submitRosterRemarkModifiyToServer(
                        remark, mobileNum, moreDesc, localUserInfo.getUser_uid(), friendUidForInit);
            }
            else{
                ToolKits.fetalErrorAlert(context);
                return DataFromServer.createDefaultFailed();
            }
        }

        /**
         * 处理服务端返回的登陆结果信息.
         */
        protected void onPostExecuteImpl(Object result) {
            boolean updateSucess = "1".equals((String)result);
            if(updateSucess) {
                WidgetUtils.showToast(FriendRemarkEditActivity.this, $$(R.string.general_update_successfully), WidgetUtils.ToastType.OK);

                // 更新缓存在内存里的好友信息
                friendInfo.setFriendRemark(editRemark.getText().toString().trim());
                friendInfo.setFriendMobileNum(editMobileNum.getText().toString().trim());
                friendInfo.setFriendMoreDesc(editMoreDesc.getText().toString().trim());

                // 更新首页"消息"列表中的显示
                AlarmsProvider ap = MyApplication.getInstance2().getIMClientManager().getAlarmsProvider();
                if(ap != null){
                    ap.updateAlarmTitle(AlarmType.friendChat, friendInfo.getUser_uid(), friendInfo.getNickNameWithRemark(), true);
                }

                // 通知ui界面进行刷新(首页、好友列表、聊天界面)
                BroadcastToolKits.friendRemarkChanged_SEND(MyApplication.getInstance2(), friendInfo.getUser_uid(), friendInfo.getNickNameWithRemark());

                // 关闭本编辑界面
                FriendRemarkEditActivity.this.setResult(Activity.RESULT_OK);
                FriendRemarkEditActivity.this.finish();
            }
            else {
                WidgetUtils.showToast(FriendRemarkEditActivity.this, $$(R.string.general_update_fail), WidgetUtils.ToastType.ERROR);
            }
        }
    }
}
